const { Recipe, User } = require('../models');
const { Op } = require('sequelize');
const { calculateBMR, getRecommendationType } = require('../utils/healthUtils');

module.exports = {
  // 获取食谱列表
  async getRecipes(req, res) {
    try {
      const { page = 1, limit = 10, search, category } = req.query;
      const offset = (page - 1) * limit;

      const where = {};
      if (search) {
        where.name = {
          [Op.like]: `%${search}%`
        };
      }
      if (category) {
        where.category = category;
      }

      const recipes = await Recipe.findAll({
        where,
        include: [{
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatar']
        }],
        limit: parseInt(limit),
        offset: parseInt(offset),
        order: [['createdAt', 'DESC']]
      });

      res.json({
        recipes,
        page: parseInt(page),
        limit: parseInt(limit)
      });
    } catch (error) {
      console.error('获取食谱列表失败:', error);
      res.status(500).json({ message: '获取食谱列表失败' });
    }
  },

  // 获取推荐食谱
  async getRecommendRecipes(req, res) {
    try {
      const user = req.user;
      const { height, weight, age, gender, goal, dietaryRestrictions = [] } = user;

      // 计算BMI
      const heightInMeters = height / 100;
      const bmi = weight / (heightInMeters * heightInMeters);

      // 计算基础代谢率(BMR)
      const bmr = calculateBMR(weight, height, age, gender);

      // 计算每日推荐摄入热量
      const dailyCalories = Math.round(bmr * 1.2); // 假设轻度活动水平

      // 获取体重建议类型
      const recommendationType = getRecommendationType(bmi);

      // 获取各餐点推荐食谱
      const breakfast = await Recipe.findAll({
        where: {
          category: '早餐'
        },
        order: [['likes', 'DESC']],
        limit: 6
      });

      const lunch = await Recipe.findAll({
        where: {
          category: '午餐'
        },
        order: [['likes', 'DESC']],
        limit: 6
      });

      const dinner = await Recipe.findAll({
        where: {
          category: '晚餐'
        },
        order: [['likes', 'DESC']],
        limit: 6
      });

      // 返回推荐结果
      res.json({
        userStats: {
          bmi: bmi.toFixed(1),
          bmr: Math.round(bmr),
          dailyCalories,
          recommendationType,
          goal,
          dietaryRestrictions
        },
        recipes: {
          breakfast,
          lunch,
          dinner
        }
      });

    } catch (error) {
      console.error('获取推荐食谱失败:', error);
      res.status(500).json({ message: '获取推荐食谱失败' });
    }
  },

  // 获取食谱详情
  async getRecipeById(req, res) {
    try {
      const recipe = await Recipe.findByPk(req.params.id, {
        include: [{
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatar']
        }]
      });

      if (!recipe) {
        return res.status(404).json({ message: '食谱不存在' });
      }

      res.json(recipe);
    } catch (error) {
      console.error('获取食谱详情失败:', error);
      res.status(500).json({ message: '获取食谱详情失败' });
    }
  },

  // 创建食谱
  async createRecipe(req, res) {
    try {
      const recipe = await Recipe.create({
        ...req.body,
        createdBy: req.user.id
      });

      res.status(201).json(recipe);
    } catch (error) {
      console.error('创建食谱失败:', error);
      res.status(500).json({ message: '创建食谱失败' });
    }
  },

  // 更新食谱
  async updateRecipe(req, res) {
    try {
      const recipe = await Recipe.findByPk(req.params.id);

      if (!recipe) {
        return res.status(404).json({ message: '食谱不存在' });
      }

      if (recipe.createdBy !== req.user.id) {
        return res.status(403).json({ message: '无权修改此食谱' });
      }

      await recipe.update(req.body);
      res.json(recipe);
    } catch (error) {
      console.error('更新食谱失败:', error);
      res.status(500).json({ message: '更新食谱失败' });
    }
  },

  // 删除食谱
  async deleteRecipe(req, res) {
    try {
      const recipe = await Recipe.findByPk(req.params.id);

      if (!recipe) {
        return res.status(404).json({ message: '食谱不存在' });
      }

      if (recipe.createdBy !== req.user.id) {
        return res.status(403).json({ message: '无权删除此食谱' });
      }

      await recipe.destroy();
      res.json({ message: '删除成功' });
    } catch (error) {
      console.error('删除食谱失败:', error);
      res.status(500).json({ message: '删除食谱失败' });
    }
  },

  // 获取我的食谱
  async getMyRecipes(req, res) {
    try {
      console.log(req, 'req.user.id');
      const recipes = await Recipe.findAll({
        where: {
          createdBy: req.user.id
        },
        order: [['createdAt', 'DESC']]
      });

      res.json({code:0,data:{recipes}});
    } catch (error) {
      console.error('获取我的食谱失败:', error);
      res.status(500).json({ message: '获取我的食谱失败' });
    }
  }
}; 